/**
 * @description 单个input模板
 * @example 股票仓位变化（基于定报）
 * @author gf
 */

import { Fragment, useEffect, useState } from "react";
import { FlexDiv, Box, Text } from "./SelectInput";
import { RedBtn } from "../Button";
import { BottomCard } from "./BottomCard";
import { collectErrors, IsExitUnit } from "./InlineInput";
import { RedTitle } from "../Title/redTitile";
import SInputNumber from "../Input/InputNumber";
import { ToFixNumber } from "@/utils/utils";

// 适合此模板的事件代码
export const EVENT_SINGLE_INPUT = [
  "stock_holding_alert_report", // 股票仓位变化（基于定报）
  "stock_holding_alert_predicted", // 股票仓位变化（预测）
  "duration_alert_interestrate", //久期变化（利率风险）
  "portfolio_section_concentration_zz", // "板块集中度"
  "fund_profit_potential", // "货基收益提醒"
  "fund_profit_risk1", // "货基风险提醒一"
  "bond_deviate_valuation_negative_change", // 债券价格负偏离
  "bond_deviate_valuation_positive_change", // "债券价格正偏离"
];

const PLACEHOLDER_1 = {
  // 第一部分文本
  stock_holding_alert_report: "定期报告披露股票持仓，变化",
  stock_holding_alert_predicted: "根据基金股票仓位预测的股票持仓，变化",
  duration_alert_interestrate:
    "最新定期报告利率测算久期与近六个报告期测算久期偏离超过", //久期变化（利率风险）
  portfolio_section_concentration_zz: "组合第一大板块占比>",
  bond_deviate_valuation_negative_change:
    "基金底层持仓债券中证/中债估值与实际成交价格偏离≤",
  bond_deviate_valuation_positive_change:
    "基金底层持仓债券中证/中债估值与实际成交价格偏离≥",
  fund_profit_potential: "基金披露的偏离度平均值在同类基金所在排名（从大到小）分位前",
  fund_profit_risk1: "基金披露的偏离度最大值<0, 且偏离度绝对值平均值在同类基金所在排名（从大到小）分位前",
};

const PLACEHOLDER_2 = {
  // 第二部分文本
  stock_holding_alert_report: "%以上",
  stock_holding_alert_predicted: "%以上",
  duration_alert_interestrate: "年",
  portfolio_section_concentration_zz: "%",
  fund_profit_potential: "%",
  fund_profit_risk1: "%",
  bond_deviate_valuation_negative_change: "%",
  bond_deviate_valuation_positive_change: "%",
};

const UNIT_LIST = [
  // 所有事件的单位全集
  "%",
  "年",
];

const SingleInput = (props: any) => {
  const { thresholdValue, onSubmit, eventInfo, enable } = props;
  const [saveParams, setSaveParams] = useState({
    threshold: "",
  });
  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);

  useEffect(() => {
    setSaveParams({
      threshold: thresholdValue?.threshold,
    });
    setIsChanged(false);
    setErrorList([]);
  }, [thresholdValue]);

  useEffect(() => {
    if (enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true);
    }
  }, [enable]);

  const onChange = (val: string, key: string) => {
    console.log(val, typeof val);
    handleCollectErrors(val, key);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || "",
      };
    });
  };

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams);
    setErrorList([...new Set(res)]);
    return [...new Set(res)];
  };

  const onClick = () => {
    const res = handleCollectErrors();
    if (errorList.length > 0 || res.length > 0) return;
    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: saveParams,
      dataMemo: createText(false),
    });
  };

  const createText = (html: Boolean) => {
    // 创建文案
    let str = ` <p>
    * ${PLACEHOLDER_1[eventInfo.value]}
    <em>
      ${ToFixNumber(saveParams.threshold)}
      ${IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST)}
    </em>
    ${PLACEHOLDER_2[eventInfo.value].replace(
      IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST),
      ""
    )} 。
  </p>`;
    if (!html) {
      str = str
        .replaceAll("<p>", "")
        .replaceAll("</p>", "")
        .replaceAll("<em>", "")
        .replaceAll("</em>", "")
        .replaceAll("\n", "")
        .replaceAll(" ", "");
    }
    return str;
  };

  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <Text>{PLACEHOLDER_1[eventInfo.value]}</Text>
          <SInputNumber
            value={saveParams.threshold}
            isError={errorList.includes("threshold")}
            onChange={(e) => onChange(e, "threshold")}
            min={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "年"
                ? 0
                : -100
            }
            max={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "年"
                ? 1000
                : 100
            }
            precision={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "年"
                ? 0
                : 2
            }
          />
          <Text>{PLACEHOLDER_2[eventInfo.value]}</Text>
        </FlexDiv>
        <BottomCard info={createText(true)} />
      </Box>
      <FlexDiv style={{ marginTop: 12, alignItems: "flex-end" }}>
        <RedBtn disabled={!isChanged} onClick={!isChanged ? null : onClick}>
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged && <RedTitle eventInfo={eventInfo} />}
      </FlexDiv>
    </Fragment>
  );
};

export default SingleInput;
